//
//  BBBlobDrawView.m
//  xNose
//
//  Created by ben smith on 1/10/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BBBlobDrawView.h"
#import "BBTUIOCursor.h"
#import "BBNodeController.h"


@implementation BBBlobDrawView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(drawBlobsNotification:) name:@"BBTUIOCursors" object:nil];
			trash = [[NSImage imageNamed:@"trash.png"] retain];

    }
    return self;
}


-(void)setDrawTrash:(BOOL)b
{
	drawTrash = b;
	[self setNeedsDisplay:YES];
}


-(void)drawBlobsNotification:(NSNotification*)sender
{
	if (blobEvents == nil) blobEvents = [[NSMutableArray alloc] init];
	NSArray * blobs = [sender object];
	// first check:
	NSInteger preCount = [blobEvents count];
	[blobEvents removeAllObjects];
	[blobEvents addObjectsFromArray:[sender object]];
	if (([blobs count] == 0) && (preCount > 0)) {
		[self setNeedsDisplay:YES];
		return;
	}
	if ([blobEvents count] > 0) {
		[self setNeedsDisplay:YES];		
	}
}


- (void)drawRect:(NSRect)rect {
    // Drawing code here.
	if ([blobEvents count] > 0) [self drawBlobEvents];
	if (drawTrash) {
		[trash drawInRect:[[BBNodeController sharedNodeController] trashRect]
						 fromRect:NSZeroRect 
						operation:NSCompositeSourceOver 
						 fraction:1.0];
	}
}

-(void)drawBlobEvents
{
	for (BBTUIOCursor* cursor in blobEvents) {
		NSRect frame = [self frame];
		NSPoint location = [cursor position];
		
		location.x *= NSWidth(frame);
		location.y = NSHeight(frame) - (location.y * NSHeight(frame));
		[self drawSingleBlob:location];
	}
}

-(void)drawSingleBlob:(NSPoint)p
{
	float radius = 20;
	NSRect r = NSMakeRect(p.x - radius, p.y - radius, radius + radius, radius + radius);
	
	NSBezierPath * circle = [NSBezierPath bezierPathWithOvalInRect:r];
	float array[2];
	array[0] = 5.0; //segment painted with stroke color
	array[1] = 5.0; //segment not painted with a color
	
	[circle setLineDash:array count: 2 phase: 0.0];
	[circle setLineWidth:2.0];
	[[NSColor yellowColor] set];
	[circle stroke];
}

- (void) dealloc
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super dealloc];
}

@end
